package com.immediatus.engine.image;

import com.immediatus.engine.primitive.BaseRectangle;
import com.immediatus.graphics.buffer.TextureRegionBuffer;
import com.immediatus.graphics.camera.Camera;
import com.immediatus.graphics.texture.region.BaseTextureRegion;
import com.immediatus.graphics.util.OpenGLWrapper;
import com.immediatus.graphics.vertex.RectangleVertexBuffer;

import javax.microedition.khronos.opengles.GL10;

public abstract class BaseImageLabel extends BaseRectangle{

    private final BaseTextureRegion _textureRegion;

    public BaseImageLabel(final float x_, final float y_, final float w_, final float h_, final BaseTextureRegion textureRegion_){
        super(x_, y_, w_, h_);

        this._textureRegion = textureRegion_;
        this.initBlendFunction();
    }

    public BaseImageLabel(final float x_, final float y_, final float w_, final float h_, final BaseTextureRegion textureRegion_, final RectangleVertexBuffer rectangleVertexBuffer_){
        super(x_, y_, w_, h_, rectangleVertexBuffer_);

        this._textureRegion = textureRegion_;
        this.initBlendFunction();
    }

    public BaseTextureRegion getTextureRegion(){
        return this._textureRegion;
    }

    public void setFlippedHorizontal(final boolean flipped_){
        this._textureRegion.setFlippedHorizontal(flipped_);
    }

    public void setFlippedVertical(final boolean flipped_){
        this._textureRegion.setFlippedVertical(flipped_);
    }

    @Override
    public void reset(){
        super.reset();
        this.initBlendFunction();
    }

    @Override
    protected void onInitDraw(final GL10 gl_){
        super.onInitDraw(gl_);
        OpenGLWrapper.enableTextures(gl_);
        OpenGLWrapper.enableTexCoordArray(gl_);
    }

    @Override
    protected void doDraw(final GL10 gl_, final Camera camera_){
        this._textureRegion.onApply(gl_);
        super.doDraw(gl_, camera_);
    }

    @Override
    protected void finalize() throws Throwable{
        super.finalize();

        final TextureRegionBuffer textureRegionBuffer = this._textureRegion.getTextureBuffer();
        if (textureRegionBuffer.isManaged()){
            textureRegionBuffer.unloadFromActiveBufferObjectManager();
        }
    }

    private void initBlendFunction(){
        if (this._textureRegion.getTexture().getTextureOptions()._PreMultipyAlpha){
            this.setBlendFunction(BLENDFUNCTION_SOURCE_PREMULTIPLYALPHA_DEFAULT, BLENDFUNCTION_DESTINATION_PREMULTIPLYALPHA_DEFAULT);
        }
    }
}
